import { defineStore } from 'pinia'
import { 
  getToken, setToken, removeToken,
  getRefreshToken, setRefreshToken, removeRefreshToken,
  getUserInfo, setUserInfo, removeUserInfo
} from '@/utils/auth'
import type { LoginUser, UserInfo } from '@/types/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: getToken() || '',
    refreshToken: getRefreshToken() || '',
    userInfo: getUserInfo() || {} as UserInfo,
    permissions: [] as string[],
    roles: [] as string[]
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.roles.includes('admin')
  },
  
  actions: {
    // 设置Token
    setToken(token: string) {
      this.token = token
      setToken(token)
    },
    
    // 设置RefreshToken
    setRefreshToken(refreshToken: string) {
      this.refreshToken = refreshToken
      setRefreshToken(refreshToken)
    },
    
    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
      setUserInfo(userInfo)
    },
    
    // 设置用户详细信息（包括权限、角色）
    setUserDetail(userDetail: LoginUser) {
      if (userDetail) {
        // 更新用户基本信息
        const userInfo = {
          userId: userDetail.userId,
          username: userDetail.userName,
          nickname: userDetail.nickName,
          avatar: userDetail.avatar,
          email: userDetail.email,
          phonenumber: userDetail.phonenumber
        } as UserInfo
        
        this.setUserInfo(userInfo)
        
        // 更新权限和角色
        this.permissions = userDetail.permissions || []
        this.roles = userDetail.roles || []
      }
    },
    
    // 清除认证信息
    clearAuth() {
      this.token = ''
      this.refreshToken = ''
      this.userInfo = {} as UserInfo
      this.permissions = []
      this.roles = []
      
      removeToken()
      removeRefreshToken()
      removeUserInfo()
    }
  }
})
